package com.heima.admin.gateway.filter;


import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {


    //全局过滤器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1. 获取request 和 response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2. 判断是否登录
        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            //放行
            return chain.filter(exchange);
        }
        //3. 获取token
        String token = request.getHeaders().getFirst("token");
        //4. 判断token是否为空
        if (StringUtils.isBlank(token)) {

            log.info("当前请求{}未登录不能访问", request.getURI().getPath());
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束请求
            return response.setComplete();
        }
        //5. 判断token是否有效
        Object userId = null;
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //是否是过期  -1：有效，0：有效，1：过期，2：过期
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result == 1 || result == 2) {
                //返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束请求
                return response.setComplete();
            }
            //TODO 获取后台管理端用户id
            //获取用户信息( 后台管理员的id
            userId = claimsBody.get("id");
            //存入header中
            Object finalUserId = userId;
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", finalUserId + "");
            }).build();
            //重置请求
            exchange.mutate().request(serverHttpRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //6. 放行
        log.info("[后台管理端:]用户{}--请求了路径{}", userId, request.getURI().getPath());
        return chain.filter(exchange);
    }

    /**
     * 优先级设置 值越小 优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }


}
